package cn.cnsy123.shorturls.business.component;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.cnsy123.shorturls.business.exception.RequestUrlNotFoundException;

public class ShortConvertService {
    
    private static final Logger logger = LoggerFactory.getLogger(ShortConvertService.class);
    private static String[] chars = new String[]{
            "a", "b", "c", "d", "e", "f", "g", "h",
            "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
            "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
            "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T",
            "U", "V", "W", "X", "Y", "Z"
    };
    
    public String shortUrl(String sourceUrl) {
        logger.info("地址转换请求:{}",sourceUrl);
        if(StringUtils.isBlank(sourceUrl)) {
            throw new RequestUrlNotFoundException("需转换地址不存在");
        }
        StringBuilder sourceStr = new StringBuilder();
        sourceStr.append(sourceUrl);
        sourceStr.append(System.currentTimeMillis());
        sourceStr.append(RandomStringUtils.random(16));
        String md5Result = DigestUtils.md5Hex(sourceStr.toString());
        String [] shortAddr = new String [4];
        for(int i = 0; i < 4; i++) {
            String tmp = md5Result.substring(i * 8, i * 8 + 8);
            long lHexLong = 0x3FFFFFFF & Long.parseLong(tmp, 16);
            String outChars = "";
            //循环获得每组6位的字符串
            for (int j = 0; j < 6; j++) {
            // 把得到的值与 0x0000003D 进行位与运算，取得字符数组 chars 索引(具体需要看chars数组的长度   以防下标溢出，注意起点为0)
            long index = 0x0000003D & lHexLong;
            // 把取得的字符相加
            outChars += chars[(int) index];
            // 每次循环按位右移 5 位
            lHexLong = lHexLong >> 5;
            }
            shortAddr[i] = outChars;
        }
        int index = RandomUtils.nextInt(0, 4);
        logger.info("完成转换地址为:{}",shortAddr[index]);
        return shortAddr[index];
    }

}
